package cn.simple.filetools.controller;

import cn.simple.filetools.exception.ReadExcelException;
import cn.simple.filetools.model.entty.Test;
import cn.simple.filetools.poi.excel.support.DefaultPoiExcelReadListener;
import cn.simple.filetools.poi.excel.support.DefaultPoiExcelWriteProcessor;
import cn.simple.filetools.poi.excel.support.ExcelHandler;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.apache.poi.openxml4j.opc.internal.ContentTypeManager;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author jiangjinjian
 * @date 2024/8/28 11:46
 * @description 测试控制层
 */
@RestController
@RequestMapping("test")
public class TestController {

    @PostMapping("readExcel")
    public void readExcel(@RequestParam("file") MultipartFile file) {
        ExcelHandler<Test> handler = ExcelHandler.create(new DefaultPoiExcelReadListener<>(Test.class), new DefaultPoiExcelWriteProcessor<>());
        try (InputStream inputStream = file.getInputStream()) {
            System.out.println(handler.read(inputStream).getData());
        } catch (IOException e) {
            throw new ReadExcelException(e);
        }
    }

    @PostMapping("writeExcel")
    public void writeExcel(HttpServletResponse response) {
        try {
            ServletOutputStream os = response.getOutputStream();
            DefaultPoiExcelReadListener<Test> readListener = new DefaultPoiExcelReadListener<>(Test.class);
            ExcelHandler<Test> handler = ExcelHandler.create(readListener, new DefaultPoiExcelWriteProcessor<>());

            List<Test> data = Stream.iterate(0, i -> i + 1)
                    .limit(19)
                    .map(i -> {
                        Test test = new Test();
                        test.setAttr1("1" + i);
                        test.setAttr2("2" + i);
                        test.setAttr34("3" + i);
                        return test;
                    }).collect(Collectors.toList());
            ByteArrayOutputStream outputStream = (ByteArrayOutputStream)handler.write(data);
            os.write(outputStream.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
